package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.sercice.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("login")
    public R login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.判断用户输入的账号和密码是否为空
        if (employee == null || StringUtils.isEmpty(employee.getUsername()) || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("用户名或密码不能为空");
        }
        //2. 获取用户输入的密码  并加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //3.根据用户输入的用户信息的username 从数据库中获取用户的数据信息
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        //比较之后 获取到数据库中的那一个用户数据
        Employee emp = employeeService.getOne(wrapper);
        //4. 判断 数据库中没有用户输入的账号 登陆失败 ,返回y用户不存在
        if (emp == null) {
            return R.error("账号不存在");
        }
        //5. 输入的密码和数据库中的密码不一致
        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误,请重新输入");
        }
        //6. 账号的状态为  0--禁用   1 --可用
        if (emp.getStatus() == 0) {
            return R.error("账号已被禁用");
        }
        //7.登录成功 放到session中并返回登录成功提示
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * 退出  点击退出把会话中的数据清除 并退出页面
     *
     * @param request
     * @return
     */
    @PostMapping("logout")
    public R logout(HttpServletRequest request) {
        //1.第一种 把会话直接删除
        //request.getSession().invalidate();
        //2. 第二种 清除会话内容
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping
    public R save( @RequestBody Employee employee) {
        log.info("新增员工，员工信息：{}", employee.toString());
        //s设置初始密码并且加密
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //设置修改数据时间和创建时间
       /* employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());

        //从session中获取修改人的信息
        Long empId = (Long) request.getSession().getAttribute("employee");
        //设置修改人和保存人
        employee.setUpdateUser(empId);
        employee.setCreateUser(empId);
*/
        //调用方法
        employeeService.save(employee);
        //返回信息
        return R.success("员工添加成功");





      /*  log.info("新增员工，员工信息：{}", employee.toString());

        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //获得当前登录用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");

        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("新增员工成功");*/
    }

    /**
     * 员工信息分页查询
     * @param page     当前查询页码
     * @param pageSize 每页展示记录数
     * @param name     员工姓名 - 可选参数
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        // log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        //QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        // wrapper.like(StringUtils.isNotEmpty(name),"name",name);
        wrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        // wrapper.orderByDesc("getUpdateTime");
        wrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, wrapper);

        //从pageInfo中获取到需要的 list 集合 records   和 total 总记录数
        //返回结果
        return R.success(pageInfo);
    }

    /**
     * 启用.禁用员工账号
     * @param employee
     * @return
     */
    @PutMapping
    public R update( @RequestBody Employee employee) {
        log.info("修改信息!"+employee.toString());
/*        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);
*/
        employeeService.updateById(employee);
        return R.success("修改成功");

    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        log.info("根据id查询员工信息");
        //根据id查询到员工信息
        Employee employee = employeeService.getById(id);
        //判断---如果查询到就返回成功  没有查询到就返回没有查询到
        if (employee != null) {
            return R.success(employee);
        } else {
            return R.success("没有查询到对应的员工信息");
        }
    }




    @GetMapping("/export")
    public void execl(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition","attachment; filename=export.xlsx");

        List<Employee> list = employeeService.list();
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream,Employee.class).sheet("员工数据").doWrite(list);

    }




}
